import themeChangeBehavior from 'tdesign-miniprogram/mixins/theme-change';
const pagePermissionMixin = require('../../utils/page-permission-mixin.js');
const { MODULES } = require('../../utils/permission.js');
const { getMonthlySalary, getDailySalaryList } = require('../../utils/salary-query-api.js');

Page({
  behaviors: [themeChangeBehavior],
  
  // 混入权限检查方法
  ...pagePermissionMixin,
  
  data: {
    userInfo: null,
    selectedMonth: '',
    salaryData: null,
    showMonthPicker: false,
    monthLabels: [],     // 显示标签数组
    monthValues: [],     // 实际值数组  
    pickerIndex: 0,      // 当前选中索引
    selectedMonthLabel: '', // 当前显示的月份标签
    statistics: {
      totalWorkDays: 0,
      totalWorkHours: 0,
      totalPieces: 0,
      totalAmount: 0,
      averageDaily: 0
    },
    detailList: [],
    loading: false,
    noData: false
  },

  onLoad() {
    // 检查页面权限
    this.onPageLoadPermissionCheck(MODULES.SALARY_QUERY);
    // 初始化基础数据
    this.loadUserInfo();
    this.initMonthOptions();
    this.initCurrentMonth();
    // 加载当前月工资数据
    this.loadSalaryData();
  },

  onShow() {
    // 页面显示时不自动刷新，由用户手动触发
  },



  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo') || { 
      name: '系统管理员', 
      employeeNumber: '001', 
      account: '001' 
    };
    
    if (!userInfo.role && !userInfo.employeeNumber && !userInfo.account) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }   
    this.setData({ userInfo });
  },

  initMonthOptions() {
    const labels = [];
    const values = [];
    const currentDate = new Date();
    
    // 生成最近12个月的选项
    for (let i = 0; i < 12; i++) {
      const date = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const monthStr = `${year}-${String(month).padStart(2, '0')}`;
      const label = `${year}年${month}月`;
      
      labels.push(label);
      values.push(monthStr);
    }
    
    this.setData({ 
      monthLabels: labels,
      monthValues: values,
      selectedMonthLabel: labels[0]
    });
  },

  initCurrentMonth() {
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    const monthStr = `${year}-${String(month).padStart(2, '0')}`;
    const monthLabel = `${year}年${month}月`;
    
    this.setData({ 
      selectedMonth: monthStr,
      selectedMonthLabel: monthLabel,
      pickerIndex: 0
    });
  },



  async loadSalaryData() {
    const { selectedMonth, userInfo } = this.data;
    
    if (!userInfo || !userInfo.employeeNumber && !userInfo.account) {
      wx.showToast({
        title: '用户信息不完整',
        icon: 'none'
      });
      return;
    }

    // 获取员工账号
    const employeeAccount = userInfo.employeeNumber || userInfo.account;
    
    this.setData({ loading: true, noData: false });
    wx.showLoading({ title: '加载中...' });
    
    try {
      // 并行请求月度总收入和每日工资列表
      const [monthlyResult, dailyResult] = await Promise.all([
        getMonthlySalary(selectedMonth, employeeAccount),
        getDailySalaryList(selectedMonth, employeeAccount)
      ]);

      // 改进逻辑：即使其中一个API失败，也尝试显示可用的数据
      if (monthlyResult.success || dailyResult.success) {
        // 处理月度数据（如果可用）
        const salaryData = monthlyResult.success 
          ? this.formatMonthlySalaryData(monthlyResult.data, selectedMonth, userInfo)
          : null;
        
        // 处理每日详情数据（如果可用）
        const detailList = dailyResult.success 
          ? this.formatDailySalaryData(dailyResult.data)
          : [];
        
        // 计算统计信息
        const statistics = this.calculateStatistics(detailList, salaryData);

        this.setData({
          salaryData,
          detailList,
          statistics,
          noData: !salaryData && detailList.length === 0
        });


        
        // 如果部分数据失败，给用户提示
        if (!monthlyResult.success || !dailyResult.success) {
          const partialMessage = !monthlyResult.success 
            ? '月度汇总数据获取失败，仅显示每日明细'
            : '每日明细数据获取失败，仅显示月度汇总';
            
          wx.showToast({
            title: partialMessage,
            icon: 'none',
            duration: 1500
          });
        }
        
      } else {
        console.warn('⚠️ 工资数据获取失败:', {
          monthlySuccess: monthlyResult.success,
          monthlyMessage: monthlyResult.message,
          dailySuccess: dailyResult.success,
          dailyMessage: dailyResult.message
        });
        
        // 提供更友好的错误信息
        let errorMessage = '获取工资数据失败';
        if (!monthlyResult.success && !dailyResult.success) {
          errorMessage = '月度和每日工资数据获取失败';
        } else if (!monthlyResult.success) {
          errorMessage = monthlyResult.message || '月度工资数据获取失败';
        } else if (!dailyResult.success) {
          errorMessage = dailyResult.message || '每日工资数据获取失败';
        }
        
        wx.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        });
        
        this.setData({
          salaryData: null,
          detailList: [],
          noData: true
        });
      }
    } catch (error) {
      console.error('❌ 工资数据加载异常:', error);
      
      wx.showToast({
        title: '网络异常，请重试',
        icon: 'none',
        duration: 2000
      });
      
      this.setData({
        salaryData: null,
        detailList: [],
        noData: true
      });
    } finally {
      this.setData({ loading: false });
      wx.hideLoading();
    }
  },



  // 格式化月度工资数据
  formatMonthlySalaryData(data, selectedMonth, userInfo) {
    if (!data) return null;


    return {
      month: selectedMonth,
      employeeName: userInfo.name || '未知',
      employeeId: userInfo.employeeNumber || userInfo.account || 'E001',
      basicSalary: parseFloat(data.basicSalary || 0),
      pieceworkSalary: parseFloat(data.pieceworkSalary || data.totalAmount || 0),
      bonus: parseFloat(data.bonus || 0),
      overtime: parseFloat(data.overtime || 0),
      deductions: parseFloat(data.deductions || 0),
      totalSalary: parseFloat(data.totalSalary || data.totalAmount || 0),
      status: data.status || 'paid',
      payDate: data.payDate || data.createTime || '',
      workDays: parseInt(data.workDays || 0),
      workHours: parseFloat(data.workHours || 0),
      totalPieces: parseInt(data.totalPieces || data.quantity || 0)
    };
  },

  // 格式化每日工资数据
  formatDailySalaryData(data) {

    if (!data || !Array.isArray(data)) {
      return [];
    }

    // 过滤掉工资为0的日期，只显示有收入的日期
    return data
      .filter(item => parseFloat(item.amount || 0) > 0)
      .map(item => ({
        date: item.day || item.date || '',
        amount: parseFloat(item.amount || 0),
        displayDate: this.formatDisplayDate(item.day || item.date || '')
      }));
  },

  // 计算统计信息
  calculateStatistics(detailList, salaryData) {
    const statistics = {
      totalWorkDays: salaryData ? salaryData.workDays : 0,
      totalMonthSalary: 0, // 改为本月总工资
      totalPieces: salaryData ? salaryData.totalPieces : 0,
      totalAmount: salaryData ? salaryData.pieceworkSalary : 0,
      averageDaily: 0
    };

    // 从每日工资数据计算本月总工资
    if (detailList.length > 0) {
      const totalMonthSalary = detailList.reduce((sum, item) => sum + item.amount, 0);
      statistics.totalMonthSalary = totalMonthSalary;
      statistics.totalWorkDays = detailList.length; // 有收入的工作天数
    }

    // 如果没有月度数据，使用详情数据
    if (!salaryData && detailList.length > 0) {
      statistics.totalAmount = statistics.totalMonthSalary;
    }

    // 计算日均收入
    if (statistics.totalWorkDays > 0) {
      statistics.averageDaily = Math.round(statistics.totalMonthSalary / statistics.totalWorkDays);
    }

    return statistics;
  },

  // 格式化显示日期
  formatDisplayDate(dateStr) {
    if (!dateStr) return '';
    
    try {
      const date = new Date(dateStr);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
      const weekday = weekdays[date.getDay()];
      
      return `${month}月${day}日 星期${weekday}`;
    } catch (error) {
      return dateStr;
    }
  },

  // 微信原生picker选择事件
  onNativeMonthChange(e) {
    const index = parseInt(e.detail.value);
    const selectedMonth = this.data.monthValues[index];
    const selectedLabel = this.data.monthLabels[index];
    
    
    this.setData({
      pickerIndex: index,
      selectedMonth: selectedMonth,
      selectedMonthLabel: selectedLabel
    });
    
    this.loadSalaryData();
  },

  getStatusText(status) {
    const statusMap = {
      'paid': '已发放',
      'pending': '待发放',
      'calculating': '计算中'
    };
    return statusMap[status] || '未知';
  },

  getStatusColor(status) {
    const colorMap = {
      'paid': '#00A870',
      'pending': '#E37318',
      'calculating': '#0052D9'
    };
    return colorMap[status] || '#999';
  },

  onViewDetail(e) {
    const { month } = e.currentTarget.dataset;
    
    if (month === this.data.selectedMonth) {
      return; // 当前月份已经显示详情
    }

    // 切换到选中月份
    this.setData({ selectedMonth: month });
    this.loadSalaryData();
  },

  onShowSalarySlip() {
    const { salaryData } = this.data;
    if (!salaryData) return;

    const content = `
工资条详情：
员工姓名：${salaryData.employeeName}
工号：${salaryData.employeeId}
工资月份：${salaryData.month}

基本工资：¥${salaryData.basicSalary}
计件工资：¥${salaryData.pieceworkSalary}
奖金：¥${salaryData.bonus}
加班费：¥${salaryData.overtime}
扣除：¥${salaryData.deductions}

应发工资：¥${salaryData.totalSalary}
发放状态：${this.getStatusText(salaryData.status)}
发放日期：${salaryData.status === 'paid' ? salaryData.payDate : '未发放'}
    `;

    wx.showModal({
      title: '工资条',
      content: content.trim(),
      showCancel: false
    });
  },

  onShowWorkStatistics() {
    const { statistics } = this.data;
    const content = `
工作统计：
工作天数：${statistics.totalWorkDays}天
工作时长：${statistics.totalWorkHours}小时
计件收入：¥${statistics.totalAmount}
日均收入：¥${statistics.averageDaily}
    `;

    wx.showModal({
      title: '工作统计',
      content: content.trim(),
      showCancel: false
    });
  },

  formatMonth(monthStr) {
    const [year, month] = monthStr.split('-');
    return `${year}年${parseInt(month)}月`;
  },

  onPullDownRefresh() {
    this.loadSalaryData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  /**
   * 手动刷新数据
   */
  onRefreshData() {
    this.setData({
      loading: true,
      noData: false
    });
    this.loadSalaryData();
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  },

  // 查看某日详情
  onViewDayDetail(e) {
    const { date } = e.currentTarget.dataset;
    
    if (date) {
      // 使用优化的跳转方法
      const { optimizedNavigate } = require('../../utils/page-transition-optimizer.js');
      
      optimizedNavigate({
        url: `/pages/piecework-today/piecework-today?date=${date}&from=salary-query`,
        loadingText: '加载数据中...',
        beforeNavigate: () => {
        }
      }).catch(err => {

      });
    }
  }
}); 